#include "ZipManager.h"
#include "UnitTest++.h"
#include "FileUtils.h"
#include <stdio.h>
#include <unistd.h>
#include <dirent.h>
#include <glob.h>


TEST(ShouldDecompressAZipFileWhitOneFile)
{
    const char* path = "resources/decompressedZip.zip";
    const char* output = "resources/";
    ZipManager manager;
    manager.openFile(path);
    manager.decompress(output);

    const char* filePath = "resources/decompressedFile.txt";
    CHECK(isFile(filePath));
    unlink(filePath);
}

TEST(ShouldDecompressAZipFileWhitOneFileAndASlashToTheEndOfTheOutputPath)
{
    const char* path = "resources/decompressedZip.zip";
    const char* output = "resources/";
    ZipManager manager;
    manager.openFile(path);
    manager.decompress(output);

    const char* filePath = "resources/decompressedFile.txt";
    CHECK(isFile(filePath));
    unlink(filePath);
}


void readContent(const char* path, char*& buffer)
{
    FILE* file = fopen(path, "rb");
    fread(buffer, 15, sizeof(char), file);
   
}

TEST(ShouldDecompressAZipFileWithItsContent)
{
    const char* path = "resources/decompressedZip.zip";
    ZipManager manager;
    manager.openFile(path);
    manager.decompress("resources/");
    char* content = new char[100];
    const char* filePath = "resources/decompressedFile.txt";
    readContent(filePath, content);
    const char * expected = "This is a test\n";
    CHECK_EQUAL(memcmp(content,expected,15),0);
    unlink(filePath);
    delete [] content;
}

TEST(GivenAZipFileWithDirectoriesAndFilesShouldBeDecompressed)
{
    const char* path = "resources/DirectoriesZip.zip";
    const char* output = "resources/";
    ZipManager manager;
    manager.openFile(path);
    manager.decompress(output);

    const char* decompressedPath = "resources/DirectoriesZip";
    CHECK(isDirectory(decompressedPath));
    system("rm -r resources/DirectoriesZip");
}

TEST(GivenAZipFileWithMoreThat20FileShouldBeDecompressed)
{
    const char* path = "resources/TestFiles.zip";
    const char* output = "resources/";
    ZipManager manager;
    manager.openFile(path);
    manager.decompress(output);

    const char* decompressedPath = "resources/TestFiles";
    glob_t gl;
    size_t numberOfFiles;
    if(glob("resources/TestFiles/*", GLOB_NOSORT, NULL, &gl) == 0)
    {
        numberOfFiles = gl.gl_pathc;
    }
    
    int expectedNumberOfFiles = 27;
    CHECK(isDirectory(decompressedPath));
    CHECK_EQUAL(expectedNumberOfFiles, numberOfFiles);
    system("rm -r resources/TestFiles");
    globfree(&gl);
}
